<?php
class Main_Validate_UniqueItem extends Zend_Validate_Abstract
{
    /**
     * @var string
     */
    protected $_serviceName;

    /**
     * @var string
     */
    protected $_oldValue;

    /**
     * @var array
     */
    protected $_addlValues;

    /**
     * @var const
     */
    const NOT_CORRECT = 'NotCorrect';

    /**
     * @var array
     */
    protected $_messageTemplates = array(
            self::NOT_CORRECT => 'Уже существует'
        );

    /**
     * @param string $serviceName
     * @param string $oldValue       
     * @param array $addlValues 
     * @param string $message
     */
    public function __construct($serviceName, $oldValue, $addlValues = null, $mess = null)
    {
        if (!empty($mess)) {
            $this->_messageTemplates[self::NOT_CORRECT] = $mess;
        }
        $this->_serviceName       = $serviceName;
        $this->_oldValue = $oldValue;

        $this->_addlValues = $addlValues;
    }

    /**
     * @param string $value
     * @param array $context
     * @return bool
     */
    public function isValid ($value, $context = null)
    {
        // --- old and new values are equal --- {{
        if (!empty($context[$this->_oldValue])) {
            if ($value == $context[$this->_oldValue]) {
                return true;
            }
        }
        // --- old and new values are equal --- }}
        
		// --- addl values --- {{
        if (is_array($this->_addlValues)) {
            $toCheck   = array();
            foreach ($this->_addlValues as $varName => $colName) {
                $toCheck[$colName] = $context[$varName];
            }
        } else {
            $toCheck = $context[$this->_addlValues];
        }
        // --- addl values --- }}

        // --- service check --- {{
        
        //print_r($toCheck); exit;
        
        $service = new $this->_serviceName();
        if ($service->checkUnique($value, $toCheck)) {
            return true;
        }
        // --- service check --- }}

        $this->_error(self::NOT_CORRECT);

        return false;
    }
}